<template>
  <div>
    <el-container>
      <el-aside width="200px">
        <el-tree :data="currentMenuList" :props="defaultProps" @node-click="handleNodeClick">
          <template #default="{ node, data }">
            <span class="custom-tree-node">
              <span>{{ node.label }}</span>
              <span class="oper">
                <Plus class="add" @click="update('add')" />
                <Edit class="edit" @click="update('edit', node)" />
                <Delete class="del" @click="del()" />
                <!-- <el-button type="primary" :icon="Plus" circle />
                <el-button type="primary" :icon="Edit" circle />
                <el-button type="primary" :icon="Delete" circle /> -->
                <!-- <a style="margin-left: 8px" @click="remove(node, data)"> - </a> -->
              </span>
            </span>
          </template>
        </el-tree>
      </el-aside>
      <el-main>
        <el-descriptions title="系统信息" direction="vertical" :column="2" border>
          <el-descriptions-item label="菜单名称" width="200px">{{ currentNode.resourceName }}</el-descriptions-item>
          <el-descriptions-item label="path" width="200px">{{ currentNode.path }}</el-descriptions-item>
          <el-descriptions-item label="类型" width="200px">
            {{ currentNode.resourceType == 0 ? '菜单' : '按钮' }}
          </el-descriptions-item>
          <el-descriptions-item label="权重" width="200px">{{ currentNode.orderNum }}</el-descriptions-item>
        </el-descriptions>
        <div v-if="isLeaf">
          <el-button @click="addMenuBtn()">添加按钮</el-button>
        </div>
        path:{{ subBtnForm.path }}
        <div v-if="currentNode.resourceType == 0 && currentNode.menuButtonRespList?.length > 0">
          <el-table class="table" :data="currentNode.menuButtonRespList" border @selection-change="handleListSelection">
            <el-table-column type="selection" width="55" />
            <el-table-column type="index" width="55" label="序号" index />
            <el-table-column prop="resourceName" label="名称" align="center"></el-table-column>
            <el-table-column prop="path" label="url" align="center"></el-table-column>
            <el-table-column prop="width" align="center" label="操作" width="120">
              <template #default="{ row, $index }">
                <el-button text @click="editMenuBtn(row, $index)">编辑</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-main>
    </el-container>
    <el-dialog
      v-model="dialogBtnVisible"
      :title="dialogBtnTitle"
      width="50vw"
      :close-on-click-modal="false"
      :before-close="closeBtnFormModal"
    >
      <el-form ref="refBtnForm" label-width="150px" :inline="false" :model="subBtnForm" :rules="formRules" class="pr-5">
        <el-form-item label="按钮名称" prop="resourceName" :rules="formRules.isNotNull" label-position="left">
          <el-input v-model="subBtnForm.resourceName" class="widthPx-150" placeholder="请输入按钮名称" />
        </el-form-item>
        <el-form-item label="按钮类型" prop="buttonType" :rules="formRules.isNotNull" label-position="left">
          <el-select v-model="subBtnForm.buttonType" class="widthPx-150" placeholder="请选择按钮类型">
            <el-option v-for="(item, index) in btnTyps" :key="index" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="按钮URL" prop="path" :rules="formRules.isNotNull" label-position="left">
          <el-input v-model="subBtnForm.path" class="widthPx-150" placeholder="请输入按钮URL" />
        </el-form-item>
        <el-form-item label="接口路径" prop="apiPath" :rules="formRules.isNotNull" label-position="left">
          <el-input v-model="subBtnForm.apiPath" class="widthPx-150" placeholder="请输入接口路径" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeBtnFormModal">取 消</el-button>
          <el-button type="primary" @click="confirmBtnClick">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="50vw"
      :close-on-click-modal="false"
      :before-close="closeFormModal"
    >
      <el-form ref="refForm" label-width="150px" :inline="false" :model="subForm" :rules="formRules" class="pr-5">
        <el-form-item label="菜单名称" prop="resourceName" :rules="formRules.isNotNull" label-position="left">
          <el-input v-model="subForm.resourceName" class="widthPx-150" placeholder="品牌名称" />
        </el-form-item>
        <el-form-item label="菜单URL" prop="path" :rules="formRules.isNotNull" label-position="left">
          <el-input v-model="subForm.path" class="widthPx-150" placeholder="品牌的首字母" />
        </el-form-item>
        <el-form-item label="接口路径" prop="apiPath" :rules="formRules.isNotNull" label-position="left">
          <el-input v-model="subForm.apiPath" class="widthPx-150" placeholder="排序" />
        </el-form-item>
        <el-form-item label="菜单序号" prop="orderNum" :rules="formRules.isNotNull" label-position="left">
          <el-input v-model="subForm.orderNum" class="widthPx-150" placeholder="排序" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeFormModal">取 消</el-button>
          <el-button type="primary" @click="confirmClick">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, toRaw, toRefs } from 'vue'
import mockMenuData from '@/mockMenuData'
import { cloneDeep } from 'lodash'
import { Delete, Edit, Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

interface menuNode {
  id?: string
  resourceName?: string
  path?: string
  orderNum?: number
  menuButtonRespList?: []
  resourceType?: number
}
const defaultProps = {
  children: 'menuButtonRespList',
  label: 'resourceName'
}
const btnTyps = [
  {
    label: '查看',
    value: 0
  },
  {
    label: '编辑',
    value: 1
  },
  {
    label: '删除',
    value: 2
  }
]
const subForm = ref({
  resourceName: '',
  orderNum: '',
  path: '',
  parentId: '',
  apiPath: ''
})

const subBtnForm = ref({
  buttonType: '',
  resourceName: '',
  path: '',
  apiPath: ''
})
const { formRules, elMessage } = useElement()

const dialogTitle = ref('')
const dialogBtnTitle = ref('')
const dialogVisible = ref(false)
const dialogBtnVisible = ref(false)
const isLeaf = ref(false)
const refForm = $ref(null)
const refBtnForm = $ref(null)

//TODO 模拟接口数据
const menuData = cloneDeep(mockMenuData.data)
console.log('menuData', menuData)
const currentNode: any = ref<menuNode>({})

const update = (type: string, node?: any) => {
  dialogTitle.value = type === 'edit' ? '菜单编辑' : '菜单新增'
  dialogVisible.value = true

  nextTick(() => {
    if (node) {
      const data = JSON.parse(JSON.stringify(node.data))
      console.log('node', data)
      subForm.value = {
        ...data
      }
    }
  })
}

const del = () => {}
// 过滤按钮菜单
const filterMenuList = (list: any): menuNode[] => {
  if (!list || list.length === 0) return []
  let arr = []
  for (let idx = 0; idx < list.length; idx++) {
    if (list[idx].resourceType === 0) {
      if (list[idx].menuButtonRespList && list[idx].menuButtonRespList.length > 0) {
        arr.push({
          ...list[idx],
          menuButtonRespList: filterMenuList(list[idx].menuButtonRespList)
        })
      }
    }
  }
  // 重新排序
  arr = arr.sort((itemA, itemB) => itemB.orderNum - itemA.orderNum)
  return arr
}
// 查找菜单对应按钮
const findIteratorNode = (list: any, id: number) => {
  let res: menuNode = {}
  for (let i = 0; i < list.length; i++) {
    if (list[i].id == id) {
      res = list[i]
      console.log('list[i]', list[i])
      return list[i]
    } else if (list[i].menuButtonRespList && list[i].menuButtonRespList.length > 0) {
      res = findIteratorNode(list[i].menuButtonRespList, id)
    }
    if (res) break
  }
  return res
}

const currentMenuList = filterMenuList(menuData)
console.log('currentMenuList', currentMenuList)

const handleNodeClick = (data: any, treeNode: any) => {
  isLeaf.value = treeNode.isLeaf
  // 通过接口获取数据，目前使用模拟数据
  currentNode.value = findIteratorNode(menuData, data.id) || []
  console.log('currentNode', currentNode.value)
}

const handleListSelection = (row: menuNode) => {}

const editMenuBtn = (row, index) => {
  console.log('row', row)

  dialogBtnTitle.value = '编辑'
  dialogBtnVisible.value = true
  nextTick(() => {
    const data = JSON.parse(JSON.stringify(row))
    subBtnForm.value = {
      ...data,
      buttonType: data.resourceType
    }
    console.log('subBtnForm', subBtnForm)
  })
}
const addMenuBtn = () => {
  dialogBtnVisible.value = true
  dialogBtnTitle.value = '新增'
}

const closeFormModal = () => {
  refForm.resetFields()
  console.log('refForm', refForm)
  dialogVisible.value = false
}
const closeBtnFormModal = () => {
  refBtnForm.resetFields()
  dialogBtnVisible.value = false
}
const confirmBtnClick = () => {
  closeBtnFormModal()
  ElMessage({
    message: '成功',
    type: 'success'
  })
  console.log('subBtnForm', subBtnForm)
}
const confirmClick = () => {
  closeFormModal()
  ElMessage({
    message: '成功',
    type: 'success'
  })
  console.log('subBtnForm', subForm)
}
</script>
<style lang="scss" scoped>
.custom-tree-node {
  width: 80%;
  height: 25px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  &:hover {
    background: #f5f7fa;
    .oper {
      visibility: visible;
    }
  }
  .oper {
    visibility: hidden;
    svg {
      width: 16px;
      height: 16px;
      margin-right: 8px;
      zoom: 1;
      &:hover {
        zoom: 1.3;
      }
    }
  }
}
</style>
